import vscode, { TextDocument, Position, ExtensionContext, CancellationToken } from 'vscode';
import path from 'path';
import fs from 'fs';
import { getBasePath } from '../util/index';
import config from '../config';

function matchTagFile(projectPath: string, _path: string) {
  let destPath = path.join(projectPath, _path);
  if (!destPath.endsWith(`.${config.xmlSuffix}`)) {
    destPath += `.${config.xmlSuffix}`;
  }
  console.log("[tag]", destPath);
  if (fs.existsSync(destPath)) {
    return new vscode.Location(vscode.Uri.file(destPath), new vscode.Position(0, 0));
  }
}

/**
 * 查找文件定义的provider，匹配到了就return一个location，否则不做处理
 */
function provideDefinition(document: TextDocument, position: Position, token: CancellationToken) {
  const fileName = document.fileName;
  const line = document.lineAt(position);
  const projectPath = getBasePath(document);

  // 只处理package.json文件
  if (fileName.endsWith(".json")) {
    try {
      const json = JSON.parse(document.getText());
      if (json.usingComponents) {
        const match = line.text.match(/"([^.]+)"\s*:\s*"([^.]+)"/);
        if (match && match[1] && json.usingComponents[match[1]] && match[2]) {
          return matchTagFile(projectPath, match[2]);
        }
      }
    } catch (error) {
      console.log("[tag]", error);
    }
  } else if (fileName.endsWith(config.xmlSuffix)) {

    const workDir = path.dirname(fileName);
    const word = document.getText(document.getWordRangeAtPosition(position, /[\w-]+/g));

    const jsonFile = path.join(workDir, `${path.basename(fileName, `.${config.xmlSuffix}`)}.json`);
    if (fs.existsSync(jsonFile)) {
      const code = fs.readFileSync(jsonFile, 'utf-8');
      try {
        const json = JSON.parse(code);
        console.log(json, json.usingComponents, word);
        if (json.usingComponents && json.usingComponents[word]) {
          return matchTagFile(projectPath, json.usingComponents[word]);
        }
      } catch (error) {
        console.log("[tag]", error)
      }
    }
  }
}

/**
 * 注册标签定位
 * @param context 
 */
function registerTagLocation(context: ExtensionContext) {
  // 注册如何实现跳转到定义
  context.subscriptions.push(vscode.languages.registerDefinitionProvider(['json', config.xmlSuffix], {
    provideDefinition
  }));
}

export default registerTagLocation;